package com.chen.common.nacos;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import lombok.extern.slf4j.Slf4j;

import java.io.StringReader;
import java.util.Properties;

/**
 * 获取nacos中的配置
 * @author ChenJinLong
 */
@Slf4j
public class NacosConfigUtil {

    public static Properties getNacosConfig(NacosParam param) {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, param.getHost());
        properties.setProperty(PropertyKeyConst.USERNAME, param.getUsername());
        properties.setProperty(PropertyKeyConst.PASSWORD, param.getPassword());
        if (StrUtil.isNotBlank(param.getNamespace())){
            properties.setProperty(PropertyKeyConst.NAMESPACE, param.getNamespace());
        }

        try {
            ConfigService configService = ConfigFactory.createConfigService(properties);
            // 获取指定命名空间中的配置
            String config = configService.getConfig(param.getDataId(), param.getGroup(), 5000);
            if (config == null){
                System.err.println(StrUtil.format("nacos -> {}配置不存在! ", param));
                return null;
            }

            properties = new Properties();
            try (StringReader reader = new StringReader(config)) {
                properties.load(reader);
            }
        } catch (Exception e) {
            log.error("", e);
        }
        return properties;
    }
}
